<template>
    <div class="datetime-calculator">
        <div class="tool-header">
            <h1>日期时间计算器</h1>
            <p>计算两个日期时间之间的间隔，支持倒计时和多种单位换算</p>
        </div>

        <el-row :gutter="20">
            <el-col :span="14">
                <el-card>
                    <template #header>
                        <div class="card-header">
                            <span>时间范围</span>
                            <div class="btn-group">
                                <el-button text size="small" @click="setNow('start')">开始设为现在</el-button>
                                <el-button text size="small" @click="setNow('end')">结束设为现在</el-button>
                                <el-button type="primary" size="small" @click="calculate">计算</el-button>
                            </div>
                        </div>
                    </template>

                    <div class="form-section">
                        <el-form label-width="100px" label-position="left">
                            <el-form-item label="开始时间">
                                <el-date-picker v-model="form.start" type="datetime" placeholder="选择开始时间"
                                    format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
                                    :shortcuts="dateShortcuts" />
                            </el-form-item>

                            <el-form-item label="结束时间">
                                <el-date-picker v-model="form.end" type="datetime" placeholder="选择结束时间"
                                    format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
                                    :shortcuts="dateShortcuts" />
                            </el-form-item>

                            <el-form-item label="显示倒计时">
                                <el-switch v-model="form.showCountdown" />
                                <small class="tip">当结束时间晚于现在时自动开始倒计时刷新</small>
                            </el-form-item>
                        </el-form>
                    </div>
                </el-card>
            </el-col>

            <el-col :span="10">
                <el-card>
                    <template #header>
                        <div class="card-header">
                            <span>计算结果</span>
                            <el-button text size="small" @click="reset">重置</el-button>
                        </div>
                    </template>

                    <div v-if="result.calculated" class="result-section">
                        <div class="result-highlight">
                            <div>
                                <div class="value">{{ result.duration.days }}</div>
                                <div class="label">天</div>
                            </div>
                            <div>
                                <div class="value">{{ result.duration.hours }}</div>
                                <div class="label">小时</div>
                            </div>
                            <div>
                                <div class="value">{{ result.duration.minutes }}</div>
                                <div class="label">分钟</div>
                            </div>
                            <div>
                                <div class="value">{{ result.duration.seconds }}</div>
                                <div class="label">秒</div>
                            </div>
                        </div>

                        <el-descriptions :column="1" border>
                            <el-descriptions-item label="总毫秒数">
                                {{ result.totalMs.toLocaleString() }}
                            </el-descriptions-item>
                            <el-descriptions-item label="总小时数">
                                {{ result.totalHours.toLocaleString() }}
                            </el-descriptions-item>
                            <el-descriptions-item label="总分钟数">
                                {{ result.totalMinutes.toLocaleString() }}
                            </el-descriptions-item>
                            <el-descriptions-item label="总秒数">
                                {{ result.totalSeconds.toLocaleString() }}
                            </el-descriptions-item>
                        </el-descriptions>

                        <div v-if="countdown.active" class="countdown-card">
                            <div class="countdown-title">距结束还剩</div>
                            <div class="countdown-value">{{ countdown.display }}</div>
                        </div>
                    </div>

                    <el-empty v-else description="请选择时间并点击计算" />
                </el-card>
            </el-col>
        </el-row>

        <el-card class="info-card">
            <template #header>
                <div class="card-header">
                    <span>使用说明</span>
                </div>
            </template>
            <ul class="info-list">
                <li>计算结果精确到秒；支持跨天、跨年计算。</li>
                <li>启用倒计时后，若结束时间在未来，将自动实时刷新剩余时间。</li>
                <li>可使用快捷按钮快速将开始/结束时间设置为当前时刻。</li>
            </ul>
        </el-card>
    </div>
</template>

<script setup>
import { reactive, ref, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'

const form = reactive({
    start: '',
    end: '',
    showCountdown: true
})

const dateShortcuts = [
    {
        text: '当前时间',
        value: () => dayjs().format('YYYY-MM-DD HH:mm:ss')
    },
    {
        text: '明天此刻',
        value: () => dayjs().add(1, 'day').format('YYYY-MM-DD HH:mm:ss')
    },
    {
        text: '一周后',
        value: () => dayjs().add(7, 'day').format('YYYY-MM-DD HH:mm:ss')
    }
]

const result = reactive({
    calculated: false,
    totalMs: 0,
    totalSeconds: 0,
    totalMinutes: 0,
    totalHours: 0,
    duration: {
        days: 0,
        hours: 0,
        minutes: 0,
        seconds: 0
    }
})

const countdown = reactive({
    active: false,
    timer: null,
    display: ''
})

const setNow = (type) => {
    const now = dayjs().format('YYYY-MM-DD HH:mm:ss')
    if (type === 'start') {
        form.start = now
    } else {
        form.end = now
    }
}

const reset = () => {
    form.start = ''
    form.end = ''
    result.calculated = false
    stopCountdown()
}

const calculate = () => {
    if (!form.start || !form.end) {
        ElMessage.warning('请选择开始和结束时间')
        return
    }

    const start = dayjs(form.start)
    const end = dayjs(form.end)

    if (!end.isAfter(start)) {
        ElMessage.error('结束时间必须晚于开始时间')
        return
    }

    const diffMs = end.diff(start, 'millisecond')
    const totalSeconds = Math.floor(diffMs / 1000)
    const totalMinutes = Math.floor(totalSeconds / 60)
    const totalHours = Math.floor(totalMinutes / 60)

    const days = Math.floor(totalSeconds / (24 * 3600))
    const hours = Math.floor((totalSeconds % (24 * 3600)) / 3600)
    const minutes = Math.floor((totalSeconds % 3600) / 60)
    const seconds = totalSeconds % 60

    Object.assign(result, {
        calculated: true,
        totalMs: diffMs,
        totalSeconds,
        totalMinutes,
        totalHours,
        duration: { days, hours, minutes, seconds }
    })

    if (form.showCountdown && end.isAfter(dayjs())) {
        startCountdown(end)
    } else {
        stopCountdown()
    }
}

const updateCountdown = (target) => {
    const now = dayjs()
    if (!target.isAfter(now)) {
        countdown.display = '已到期'
        stopCountdown()
        return
    }

    const diff = target.diff(now, 'second')
    const days = Math.floor(diff / (24 * 3600))
    const hours = Math.floor((diff % (24 * 3600)) / 3600)
    const minutes = Math.floor((diff % 3600) / 60)
    const seconds = diff % 60

    countdown.display = `${days}天 ${hours}小时 ${minutes}分 ${seconds}秒`
}

const startCountdown = (target) => {
    stopCountdown()
    countdown.active = true
    countdown.timer = setInterval(() => updateCountdown(target), 1000)
    updateCountdown(target)
}

const stopCountdown = () => {
    countdown.active = false
    countdown.display = ''
    if (countdown.timer) {
        clearInterval(countdown.timer)
        countdown.timer = null
    }
}

onBeforeUnmount(() => {
    stopCountdown()
})
</script>

<style scoped>
.datetime-calculator {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
}

.tool-header {
    text-align: center;
    margin-bottom: 30px;
}

.tool-header h1 {
    font-size: 2.2rem;
    margin-bottom: 10px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: 600;
}

.btn-group {
    display: flex;
    gap: 8px;
}

.form-section {
    padding: 10px 0;
}

.result-section {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.result-highlight {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 12px;
    text-align: center;
}

.result-highlight .value {
    font-size: 2.4rem;
    font-weight: 700;
    color: #409eff;
}

.result-highlight .label {
    color: #999;
    margin-top: 4px;
}

.countdown-card {
    background: #f5f9ff;
    border: 1px solid #d3e3ff;
    border-radius: 8px;
    padding: 16px;
    text-align: center;
}

.countdown-title {
    color: #409eff;
    margin-bottom: 10px;
    font-weight: 600;
}

.countdown-value {
    font-size: 1.4rem;
    font-weight: bold;
}

.info-card {
    margin-top: 30px;
}

.info-list {
    margin: 0;
    padding-left: 20px;
    color: #666;
    line-height: 1.8;
}

.tip {
    color: #999;
    margin-left: 10px;
}

@media (max-width: 768px) {
    .result-highlight {
        grid-template-columns: repeat(2, 1fr);
    }
}
</style>
